import uvicorn
from fastapi import FastAPI, Request
from tutorial import request_app, response_app, test05_app, app05
from sql_app import sqlapp
from fastapi.responses import JSONResponse, PlainTextResponse
from fastapi.exceptions import RequestValidationError

from tutorial.exception_handler import UnicornException

# 实例化app
app = FastAPI(
    title="FastAPI学习笔记",
    description="记录学习的点点滴滴，方便日后开发",
    version='1.0.0',
    docs_url='/docs',
    redoc_url='/redocs'
)

# 注册蓝图到app中
app.include_router(request_app, prefix='/test03', tags=['第三章 请求参数和验证'])
app.include_router(response_app, prefix='/test04', tags=['第四章 响应模型'])
app.include_router(test05_app, prefix='/test05', tags=['第五章 json兼容编码器'])
app.include_router(app05, prefix='/test06', tags=['第六章 fastapi依赖注入'])
app.include_router(sqlapp, prefix='/sql', tags=['第七章 fastapi orm数据库操作'])


# 自定义异常返回格式
@app.exception_handler(UnicornException)
async def unicorn_exception_handler(request: Request, exc: UnicornException):
    """
    request: Request 这个参数不能缺少
    """
    return JSONResponse(
        status_code=418,
        content={"message": exc.message, "code": exc.code}
    )


# 重写请求验证异常处理器
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc):
    # return PlainTextResponse(str(exc), status_code=400)
    return JSONResponse(
        status_code=400,
        content={"message": str(exc), "code": 400}
    )


if __name__ == "__main__":
    uvicorn.run(app='run:app', host='0.0.0.0', port=8088, reload=True, debug=True, workers=1)
